package com.pingan.pastry.validator;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;


public class RuleBuilder {

    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    private BeanProvider beanProvider;

    private Gson gson = new Gson();

    public RuleBuilder(BeanProvider beanProvider) {
        this.beanProvider = beanProvider;
    }

    public Rule build(String uri) {
        Rule rule = new Rule();
        JsonObject config = loadConfig(uri);
        String beanName = config.get("beanName").getAsString();
        rule.setBeanName(beanName);
        try {
            List<Node> nodes = parseNode(config);
            rule.setNodes(nodes);
        } catch (FileNotFoundException e) {
            LOGGER.error("parse validators file bot found,e:" + e);
        }
        return rule;
    }

    public List<Node> parseNode(JsonObject config) throws FileNotFoundException {
        List<Node> nodes = new ArrayList<>();
        JsonObject ruleJson = config.getAsJsonObject("validateRule");
        Set<String> propertySet = ruleJson.keySet();
        for (String property : propertySet) {
            Node node = new Node();
            node.setKey(property);
            List<Validator> validators = new ArrayList<>();
            JsonArray validateJsonArray = ruleJson.getAsJsonArray(property);
            for (int i = 0; i < validateJsonArray.size(); i++) {
                JsonObject validateJson = (JsonObject) validateJsonArray.get(i);
                String beanName = validateJson.get("type").getAsString();
                JsonElement element = validateJson.get("message");
                String message = null;
                if (element != null) {
                    message = element.getAsString();
                }
                //多实例的bean
                Validator bean = (Validator) beanProvider.getBean(beanName);
                bean.setMessage(message);
                validators.add(bean);
            }
            nodes.add(node);
        }
        return nodes;
    }

    private JsonObject loadConfig(String uri) {
        String path = "rules/" + uri + ".json";
        path = path.replaceAll("/+", "/");
        JsonObject configJson;
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(path);
            configJson = gson.fromJson(new InputStreamReader(resourceAsStream), JsonObject.class);
        } finally {
            if (resourceAsStream != null) {
                try {
                    resourceAsStream.close();
                } catch (IOException e) {
                    LOGGER.error("parse rules json failed," + e.getMessage());
                    e.printStackTrace();
                }
            }
        }
        return configJson;
    }

    public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
        /*RuleBuilder ruleBuilder = new RuleBuilder();
        ruleBuilder.parseRule();
        InputStream inputStream = RuleBuilder.class.getResourceAsStream("/rules");
        BufferedReader br = null;
        StringBuffer buffer = new StringBuffer();
        try {
            br = new BufferedReader(inputStream, "UTF-8");
            int content;
            while ((content = isr.read()) != -1) {
                buffer.append(content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (isr != null) {
                    isr.close();
                }
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        System.out.println("content: "+buffer.toString());*/
    }

}
